package org.tiny.autounit.core.data.transport.server.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.tiny.autounit.core.data.transport.server.domain.NettyMessage;

import java.util.List;

/**
 * @author shichaoyang
 * @Description: 解码器
 * @date 2019-01-30 11:24
 */
public class NettyMessageDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> obj) throws Exception {
        try {
            byte[] originBytes = new byte[in.readableBytes()];
            in.readBytes(originBytes, 0, in.readableBytes());

            //去掉头部的4字节
            byte[] dstBytes = new byte[originBytes.length-4];
            System.arraycopy(originBytes,4,dstBytes,0,dstBytes.length);

            NettyMessage microMessage = SerializeUtil.deserialize(dstBytes, NettyMessage.class);
            obj.add(microMessage);
        } catch (Exception e) {
            System.out.println("exception when decoding: " + e);
        }
    }
}
